<template>
  <div class="ai-chat-wrapper">
    <!-- 悬浮按钮 -->
    <div 
      v-show="!isOpen"
      class="ai-chat-button"
      :style="buttonPosition"
      @mousedown="startDrag"
      @click="openChat">
      <el-badge :value="unreadCount" :hidden="unreadCount === 0" :max="99">
        <el-icon :size="28">
          <ChatDotRound />
        </el-icon>
      </el-badge>
      <div class="button-text">AI助手</div>
    </div>

    <!-- 对话窗口 -->
    <transition name="chat-slide">
      <div 
        v-show="isOpen" 
        class="ai-chat-window"
        :style="windowPosition">
        <!-- 标题栏 -->
        <div class="chat-header" @mousedown="startDrag">
          <div class="header-left">
            <el-icon :size="20" color="#fff">
              <ChatDotRound />
            </el-icon>
            <span class="header-title">{{ config.modelName }}</span>
          </div>
          <div class="header-actions">
            <el-button 
              text 
              size="small" 
              @click="clearHistory"
              title="清空对话">
              <el-icon><Delete /></el-icon>
            </el-button>
            <el-button 
              text 
              size="small" 
              @click="closeChat"
              title="关闭">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="chat-messages" ref="messageContainer">
          <!-- 欢迎消息 -->
          <div v-if="messages.length === 0" class="welcome-message">
            <el-icon :size="60" color="#409eff">
              <ChatDotRound />
            </el-icon>
            <p>{{ config.welcomeMessage }}</p>
          </div>

          <!-- 对话消息 -->
          <div 
            v-for="(msg, index) in messages" 
            :key="index"
            :class="['message-item', msg.role]">
            <div class="message-avatar">
              <el-icon :size="24">
                <User v-if="msg.role === 'user'" />
                <ChatDotRound v-else />
              </el-icon>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(msg.content)"></div>
              <div class="message-time">{{ msg.time }}</div>
            </div>
          </div>

          <!-- 加载中 -->
          <div v-if="isLoading" class="message-item assistant">
            <div class="message-avatar">
              <el-icon :size="24">
                <ChatDotRound />
              </el-icon>
            </div>
            <div class="message-content">
              <div class="message-loading">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入框 -->
        <div class="chat-input-wrapper">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="2"
            :placeholder="config.placeholder"
            :disabled="isLoading"
            @keydown.enter.exact.prevent="sendMessage"
            @keydown.enter.shift.exact="handleShiftEnter"
          />
          <el-button 
            type="primary" 
            :loading="isLoading"
            :disabled="!inputMessage.trim()"
            @click="sendMessage"
            class="send-button">
            <el-icon v-if="!isLoading"><Promotion /></el-icon>
            <span v-if="!isLoading">发送</span>
          </el-button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted, getCurrentInstance } from 'vue';
import { ChatDotRound, User, Close, Delete, Promotion } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance();

// 窗口状态
const isOpen = ref(false);
const isLoading = ref(false);
const unreadCount = ref(0);

// 位置相关
const isDragging = ref(false);
const dragStartX = ref(0);
const dragStartY = ref(0);
const buttonPosition = reactive({
  right: '20px',
  bottom: '20px'
});
const windowPosition = reactive({
  right: '20px',
  bottom: '20px'
});

// 消息相关
const messages = ref([]);
const inputMessage = ref('');
const messageContainer = ref(null);
const currentStreamMessage = ref('');

// AI配置
const config = reactive({
  modelName: 'AI助手',
  welcomeMessage: '你好！我是WMS智能助手，有什么可以帮助你的吗？',
  placeholder: '请输入你的问题...',
  maxHistoryLength: 10
});

// 加载配置
const loadConfig = async () => {
  try {
    const res = await proxy.http.get('/api/AIAssistant/config');
    if (res) {
      Object.assign(config, res);
    }
  } catch (error) {
    console.error('加载AI配置失败:', error);
  }
};

// 打开对话窗口
const openChat = () => {
  if (isDragging.value) return;
  isOpen.value = true;
  unreadCount.value = 0;
  nextTick(() => {
    scrollToBottom();
  });
};

// 关闭对话窗口
const closeChat = () => {
  isOpen.value = false;
};

// 清空历史
const clearHistory = () => {
  ElMessage.confirm('确定要清空所有对话记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    messages.value = [];
    ElMessage.success('对话记录已清空');
  }).catch(() => {});
};

// 开始拖拽
const startDrag = (e) => {
  isDragging.value = false;
  dragStartX.value = e.clientX;
  dragStartY.value = e.clientY;

  const currentRight = parseInt(isOpen.value ? windowPosition.right : buttonPosition.right);
  const currentBottom = parseInt(isOpen.value ? windowPosition.bottom : buttonPosition.bottom);

  const handleMouseMove = (moveEvent) => {
    isDragging.value = true;
    
    const deltaX = dragStartX.value - moveEvent.clientX;
    const deltaY = moveEvent.clientY - dragStartY.value;

    const newRight = Math.max(0, Math.min(window.innerWidth - 100, currentRight + deltaX));
    const newBottom = Math.max(0, Math.min(window.innerHeight - 100, currentBottom + deltaY));

    if (isOpen.value) {
      windowPosition.right = `${newRight}px`;
      windowPosition.bottom = `${newBottom}px`;
    } else {
      buttonPosition.right = `${newRight}px`;
      buttonPosition.bottom = `${newBottom}px`;
    }
  };

  const handleMouseUp = () => {
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
    
    setTimeout(() => {
      isDragging.value = false;
    }, 100);
  };

  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
};

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message || isLoading.value) return;

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: message,
    time: getCurrentTime()
  });

  inputMessage.value = '';
  isLoading.value = true;
  currentStreamMessage.value = '';

  // 滚动到底部
  nextTick(() => scrollToBottom());

  try {
    // 准备历史消息
    const history = messages.value
      .slice(-config.maxHistoryLength * 2)
      .map(msg => ({
        role: msg.role,
        content: msg.content
      }));

    // 构建API URL
    const apiUrl = proxy.http.ipAddress + 'api/AIAssistant/chat';
    console.log('🌐 调用AI API:', apiUrl);
    console.log('📤 发送数据:', { message, history: history.slice(0, -1) });

    // 调用后端API（SSE流式）
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: message,
        history: history.slice(0, -1) // 不包括当前消息
      })
    });
    
    console.log('📡 响应状态:', response.status, response.statusText);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 添加AI消息占位
    const aiMessageIndex = messages.value.length;
    messages.value.push({
      role: 'assistant',
      content: '',
      time: getCurrentTime()
    });

    // 读取SSE流
    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        console.log('✅ 流式响应读取完成');
        break;
      }

      const chunk = decoder.decode(value);
      const lines = chunk.split('\n');

      for (const line of lines) {
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim();
          console.log('📥 收到数据:', data.substring(0, 100) + (data.length > 100 ? '...' : ''));
          
          if (data === '[DONE]') {
            console.log('🏁 收到结束标记');
            break;
          }

          try {
            const json = JSON.parse(data);
            
            if (json.error) {
              throw new Error(json.message);
            }

            if (json.choices && json.choices[0]?.delta?.content) {
              const content = json.choices[0].delta.content;
              console.log('💬 收到内容片段:', content);
              currentStreamMessage.value += content;
              messages.value[aiMessageIndex].content = currentStreamMessage.value;
              
              // 滚动到底部
              nextTick(() => scrollToBottom());
            }
          } catch (e) {
            console.error('❌ 解析AI响应失败:', e, '原始数据:', data);
          }
        }
      }
    }

    // 如果窗口未打开，增加未读数
    if (!isOpen.value) {
      unreadCount.value++;
    }

  } catch (error) {
    console.error('❌ 发送消息失败:', error);
    console.error('错误详情:', error.message);
    console.error('错误堆栈:', error.stack);
    ElMessage.error('发送消息失败: ' + error.message);
    
    // 移除失败的AI消息
    if (messages.value[messages.value.length - 1]?.role === 'assistant') {
      messages.value.pop();
    }
  } finally {
    isLoading.value = false;
    currentStreamMessage.value = '';
    console.log('🔚 消息发送流程结束');
  }
};

// Shift+Enter换行
const handleShiftEnter = (e) => {
  // 允许默认行为（换行）
};

// 格式化消息（支持换行）
const formatMessage = (content) => {
  return content.replace(/\n/g, '<br/>');
};

// 滚动到底部
const scrollToBottom = () => {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
  }
};

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date();
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
};

// 组件挂载
onMounted(() => {
  loadConfig();
});
</script>

<style scoped lang="less">
.ai-chat-wrapper {
  position: fixed;
  z-index: 9999;
}

// 悬浮按钮
.ai-chat-button {
  position: fixed;
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: move;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  color: #fff;

  &:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
  }

  .button-text {
    font-size: 10px;
    margin-top: 2px;
  }

  :deep(.el-badge__content) {
    border: 2px solid #fff;
  }
}

// 对话窗口
.ai-chat-window {
  position: fixed;
  width: 380px;
  height: 600px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

// 动画
.chat-slide-enter-active,
.chat-slide-leave-active {
  transition: all 0.3s ease;
}

.chat-slide-enter-from,
.chat-slide-leave-to {
  opacity: 0;
  transform: scale(0.8) translateY(20px);
}

// 标题栏
.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: move;
  user-select: none;

  .header-left {
    display: flex;
    align-items: center;
    gap: 10px;
    color: #fff;

    .header-title {
      font-weight: 600;
      font-size: 16px;
    }
  }

  .header-actions {
    display: flex;
    gap: 5px;

    .el-button {
      color: #fff;
      padding: 4px;

      &:hover {
        background: rgba(255, 255, 255, 0.2);
      }
    }
  }
}

// 消息列表
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #dcdfe6;
    border-radius: 3px;
  }
}

// 欢迎消息
.welcome-message {
  text-align: center;
  padding: 60px 20px;
  color: #909399;

  p {
    margin-top: 20px;
    font-size: 14px;
    line-height: 1.6;
  }
}

// 消息项
.message-item {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  animation: messageSlide 0.3s ease;

  &.user {
    flex-direction: row-reverse;

    .message-content {
      align-items: flex-end;
    }

    .message-text {
      background: #667eea;
      color: #fff;
    }

    .message-avatar {
      background: #409eff;
    }
  }

  &.assistant {
    .message-avatar {
      background: #67c23a;
    }
  }
}

@keyframes messageSlide {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  flex-shrink: 0;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message-text {
  background: #fff;
  padding: 10px 15px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.6;
  word-wrap: break-word;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  padding: 0 5px;
}

// 加载动画
.message-loading {
  background: #fff;
  padding: 15px 20px;
  border-radius: 12px;
  display: flex;
  gap: 5px;

  .dot {
    width: 8px;
    height: 8px;
    background: #667eea;
    border-radius: 50%;
    animation: dotBounce 1.4s infinite ease-in-out both;

    &:nth-child(1) {
      animation-delay: -0.32s;
    }

    &:nth-child(2) {
      animation-delay: -0.16s;
    }
  }
}

@keyframes dotBounce {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

// 输入框
.chat-input-wrapper {
  padding: 15px;
  background: #fff;
  border-top: 1px solid #ebeef5;
  display: flex;
  gap: 10px;

  :deep(.el-textarea__inner) {
    resize: none;
    border-radius: 8px;
    font-size: 14px;
  }

  .send-button {
    align-self: flex-end;
    border-radius: 8px;
  }
}
</style>

